<template>
    <el-dialog :close-on-click-modal="false" ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible"
        width="60%" :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="疾病名称">
                        <div class="primary pointer">{{ ruleForm.diseaseName }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="12"><el-form-item label="患病鱼粒数">
                        <div class="primary pointer">{{ ruleForm.num }}粒</div>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="12"> <el-form-item label="上报人">
                        <div class="primary pointer">{{ ruleForm.staffName }}</div>
                    </el-form-item>
                </el-col> -->
                <el-col :span="12">
                    <el-form-item label="发现时间">
                        <div class="primary pointer">{{ ruleForm.happenTime }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="处方名称">
                        <div class="primary pointer">{{ ruleForm.prescriptionName }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="养殖设施温度" prop="waterTemperature">
                        <el-input type="number" :disabled="hasWaterTemperature" v-model="ruleForm.waterTemperature"
                            placeholder="请输入参数">
                            <template slot="append">℃</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="处理人" prop="staffId">
                        <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择处理人"
                            @change="handleChangePerson">
                            <el-option v-for="item, index in person" :key="index" :label="item.person.name"
                                :value="item.person.personNo"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="处理时间" prop="dealDate">
                        <el-date-picker v-model="ruleForm.dealDate" value-format="yyyy-MM-dd HH:mm:ss" align="right"
                            type="datetime" placeholder="选择时间" :picker-options="pickerOptions" @change="handleGetTime">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!isUsePrescription">
                    <el-form-item label="可选处方" prop="prescriptionId">
                        <el-select clearable v-model="ruleForm.prescriptionId" class="w100p" placeholder="请选择处方"
                            @change="handleChangePrescription">
                            <el-option v-for="item, index in diseaseBankPrescription" :key="index"
                                :label="item.prescriptionName" :value="item.prescriptionId"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-table :data="ruleForm.diseaseDealDetailList" style="width: 100%" border>
                <el-table-column prop="materialNo" label="用药名称">
                    <template slot-scope="scope">
                        <el-form-item class="hiddenLabel" :prop="`diseaseDealDetailList[${scope.$index}][materialNo]`"
                            :rules="rules.materialNo">
                            <el-select clearable filterable class=" w100p" v-model="scope.row.materialNo"
                                placeholder="请选择药品" @change="(e) => queryDrug(e, scope.$index)">
                                <el-option
                                    v-if="item.materialTypeNo == '1077222993386450944' || item.materialTypeNo == '4165464165465146516'"
                                    v-for="item, index in materialList" :key="index" :label="item.materialName"
                                    :disabled="notUseMaterial.includes(item.materialNo)"
                                    :value="item.materialNo"></el-option>
                            </el-select>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="materialNo" label="出库单号" v-if="storageRules == 'THREE'">
                    <template slot-scope="scope">
                        <el-form-item class="hiddenLabel"
                            :prop="`diseaseDealDetailList[${scope.$index}][outboundOrderIdList]`"
                            :rules="rules.outboundOrderIdList">
                            <el-select clearable filterable class=" w100p" v-model="scope.row.outboundOrderIdList"
                                placeholder="请选择出库单" @change="getOutboundOrder($event, scope.$index)" multiple>
                                <el-option v-for="order, index in outboundOrder" :key="index"
                                    :disabled="scope.row.materialNo !== order.materialNo"
                                    :label="`仓库名称：${order.stordocName}；物料名称：${order.materialName};出库单号：${order.outboundOrderNo}`"
                                    :value="order.outboundOrderId"></el-option>
                            </el-select>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="amount" label="用药数量">
                    <template slot-scope="scope">
                        <el-form-item class="hiddenLabel" :prop="`diseaseDealDetailList[${scope.$index}][amount]`"
                            :rules="rules.amount">
                            <el-input clearable type="number" :disabled="storageRules == 'THREE'"
                                v-model="scope.row.amount" placeholder="请输入用药数量">
                                <template slot="append">{{ scope.row.unitName }}</template>
                            </el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="usage" label="用药说明">
                    <template slot-scope="scope">
                        <el-form-item class="hiddenLabel" :prop="`diseaseDealDetailList[${scope.$index}][usage]`"
                            :rules="rules.usage">
                            <el-input clearable v-model="scope.row.usage" placeholder="请输入用药说明">
                            </el-input>
                        </el-form-item>
                    </template>
                </el-table-column>
                <el-table-column prop="usage" label="操作" width="120">
                    <template slot-scope="scope">
                        <el-button v-show="ruleForm.diseaseDealDetailList.length > 1" type="text"
                            @click.stop="delMaterial(scope.$index)"><span class="danger">删除</span></el-button>
                        <el-button v-show="scope.$index + 1 == ruleForm.diseaseDealDetailList.length" type="text"
                            @click.stop="addMaterial()"><span class="primary">添加</span></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
        <div class="diseaseFollowUpList" v-show="tableData.length">
            <span class="label">用药记录</span>
            <el-table :data="tableData" border style="width: 100%" height="250px">
                <el-table-column prop="staffName" label="处理人" width="180">
                </el-table-column>
                <el-table-column label="用药时水温" width="180">
                    <template slot-scope="scope">
                        {{ scope.row.waterTemperature }}℃
                    </template>
                </el-table-column>
                <el-table-column prop="dealDate" label="用药时间">
                </el-table-column>
                <el-table-column prop="lookView" label="查看详情" width="180">
                    <template slot-scope="scope">
                        <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
        <el-dialog :close-on-click-modal="false" title="用药详情列表" :visible.sync="innerVisible" append-to-body>
            <el-table :data="tableDataDiseaseDeal" border style="width: 100%">
                <el-table-column prop="materialName" label="药品名称">
                </el-table-column>
                <el-table-column label="用量">
                    <template slot-scope="scope">
                        {{ scope.row.amount }}{{ scope.row.unitName }}
                    </template>
                </el-table-column>
                <el-table-column prop="usage" label="用法">
                </el-table-column>
            </el-table>
        </el-dialog>
    </el-dialog>
</template>

<script>
import prescription from '@/api/healthManagement/prescription.js';
import diseaseFollowUp from '@/api/healthManagement/diseaseFollowUp.js';
import environmentalDataMonitoring from '@/api/iotMonitoring/environmentalDataMonitoring';
import outStorage from "@/api/livestock-manage/sale-manage/out-storage"; // 出库
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        materialList: {
            type: Array,
            default: () => {
                return []
            }
        },
        diseaseBankPrescription: {
            type: Array,
            default: () => {
                return []
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (value > 0) {
                let lastTwoDecimal = String(value).split('.');
                if (lastTwoDecimal.length == 2 && lastTwoDecimal[1].length > 2) {
                    callback(new Error('请保留小数点后两位！'));
                } else {
                    callback();
                }
            } else {
                callback(new Error('请输入大于0的数！'));
            }
        }
        return {
            storageRules: '',
            hasWaterTemperature: true,
            innerVisible: false,
            tableData: [],
            tableDataDiseaseDeal: [],
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            isUsePrescription: false,
            addEditName: '处理',
            addEditApi: '',
            ruleForm: {},
            notUseMaterial: [],
            outboundOrder: [],
            useMaterial: [],
            facility: {},
            rules: {
                materialNo: [
                    { required: true, message: '请选择药品', trigger: 'change' }
                ],
                amount: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                usage: [
                    { required: true, message: '请输入用药说明', trigger: 'change' }
                ],
                outboundOrderIdList: [
                    { required: true, message: '请选择出口单', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择处理人', trigger: 'change' }
                ],
                dealDate: [
                    { required: true, message: '请选择时间', trigger: 'change' }
                ]
            }
        }
    },
    computed: {
        person() {
            return this.$store.state.initData.person || [];
        },
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
            this.storageRules = sessionStorage.storageRules
        }
    },

    mounted() {
    },
    methods: {
        initData() {
            this.resetForm();
            if (this.addEditFlag == 'handle') {
                this.ruleForm = { ...this.data, staffId: '', staffName: '' }
                this.addEditApi = diseaseFollowUp.add;
                this.addEditName = '处理';
            } else if (this.addEditFlag == 'cProc') {
                this.ruleForm = { ...this.data, staffId: '', staffName: '' }
                this.addEditApi = diseaseFollowUp.add;
                this.addEditName = '继续处理';
            };
            if (!this.ruleForm.diseaseDealDetailList || this.ruleForm.diseaseDealDetailList.length == 0) {
                this.$set(this.ruleForm, 'diseaseDealDetailList', [{
                    materialNo: '',
                    materialName: '',
                    amount: '',
                    usage: '',
                    unitName: '',
                    outboundOrderIdList: []
                }])
            };
            let outboundOrderIds = []
            this.ruleForm.diseaseDealDetailList.forEach(e => {
                e.outboundOrderIdList = e.outOrderIds ? e.outOrderIds.split(',') : [];
                outboundOrderIds.concat(e.outboundOrderIdList)
            })
            this.isUsePrescription = !!this.ruleForm.prescriptionId;
            this.getDiseaseDealDetailList();
            this.getTableDataList();
            this.getConditionQuery(outboundOrderIds);
        },
        async getConditionQuery(outboundOrderIds = []) {
            let { data } = await outStorage.conditionQuery({ outboundOrderType: 1, relatedProduction: false, outboundOrderIds });
            this.outboundOrder = data || []
            console.log(data)
        },
        getOutboundOrder(list, index) {
            console.log(list, index)
            let orderList = this.outboundOrder.filter(e => {
                return list.includes(e.outboundOrderId)
            })
            let amount = orderList.reduce((sum, item) => sum + item.confirmQuantity, 0);
            console.log(orderList)
            let data = this.ruleForm.diseaseDealDetailList[index]
            this.$set(this.ruleForm.diseaseDealDetailList, index, {
                ...data,
                outOrderIds: list.join(),
                amount
            })
        },
        handleGetTime(e) {
            console.log(e)
            if (e && this.isToday(e)) {
                this.getDiseaseDealDetailList();
            }
        },
        // 获取数据类型-温度-酸碱度等位置及其图片
        getTableDataList() {
            console.log(this.facilityList)
            let facilityId = this.ruleForm.facilityId;
            let facilityNo = ''
            if (!facilityId) return;
            let facility = this.facilityList.find(obj => obj.facilityId == facilityId)
            facilityNo = facility.facilityNo
            this.facility = facility
            console.log(facility)
            environmentalDataMonitoring.getdataitemlisttwo(facilityNo).then((res) => {
                let data = res.data || [];
                let waterTemperature = ''
                console.log(data, '----')
                let dataItemList = this.getDataList(data);
                console.log(dataItemList)
                let dataItem = dataItemList.find(item => {
                    if (item.dataTypeId == 5) {
                        return item
                    } else {
                        return false
                    }
                })
                if (dataItem) {
                    waterTemperature = dataItem.lastValue1;
                } else {
                    waterTemperature = ''
                    this.$message.warning('未获取到设施温度，您可以手动输入当前设施的水温！')
                }
                this.hasWaterTemperature = waterTemperature ? true : false;
                this.$set(this.ruleForm, 'waterTemperature', waterTemperature)
            });
        },
        getDataList(list) {
            let newlist = []
            list.forEach((itemone, indexone) => {
                // 组织数据
                let itemonelist = [];
                itemone.dataCollectNewVOList.forEach(async (itemtwo) => {
                    let nowmessage = {};
                    nowmessage = { ...itemone.dataTypeConfig, ...itemtwo };
                    itemonelist.push({ ...nowmessage, });
                });
                newlist.push(itemonelist);
            });
            let arr = []
            newlist.forEach(el => {
                el.forEach(ell => {
                    arr.push(ell)
                })
            })
            //console.log(arr, 'arr');
            return arr
        },
        async queryDrug(no, index) {
            console.log(index)
            let res = await diseaseFollowUp.queryDrug({
                batchId: this.ruleForm.batchId,
                materialNo: no
            })
            if (res.code == 1 || this.useMaterial.includes(no)) {
                this.getMaterial();
                return
            } else if (res.code == 200) {
                this.$confirm(res.msg + '是否继续操作？', '提示', {
                    confirmButtonText: '继续使用',
                    cancelButtonText: '不使用',
                    type: 'warning'
                }).then(() => {
                    this.ruleForm.diseaseDealDetailList[index].materialNo = no
                    this.useMaterial.push(no)
                }).catch(() => {
                    this.ruleForm.diseaseDealDetailList[index].materialNo = ''
                    this.ruleForm.diseaseDealDetailList[index].materialName = ''
                    this.notUseMaterial.push(no)
                });
                this.getMaterial();
            }
        },
        async handleChangePrescription(e) {
            if (e) {
                let rut = this.diseaseBankPrescription.find(item => {
                    return item.prescriptionId == e
                })
                let { data: prescriptionList } = await prescription.findAllByPrescriptionId(e);
                let drugList = []
                let drugObj = {}
                prescriptionList.forEach(e => {
                    if (!drugObj[e.days]) {
                        drugObj[e.days] = []
                    }
                    drugObj[e.days].push(e)
                })
                for (let key in drugObj) {
                    drugList.push(drugObj[key])
                }
                let list = drugList.filter(item => {
                    return item.find(e => !e.useFlag)
                });
                console.log('最新用药', list)
                if (list.length > 0) {
                    list = list[0]
                }
                console.log(list)
                let detailList = this.ruleForm.diseaseDealDetailList || [];
                console.log(detailList)
                let scope = 1;
                let { facility } = this;
                //换算成平方米 1亩=666.666666667平方米
                if (facility.unitName == '亩') {
                    scope = Number(facility.scope || 0) * 666.666666667;
                    scope = scope.toFixed(2)
                } else if (facility.unitName == '平方米') {
                    scope = Number(facility.scope || 0)
                } else {
                    this.$message.warning('请重新配置设施单位为亩或平方米')
                    return
                }
                detailList = detailList.filter(item => {
                    return !item.prescriptionId
                })
                list = list.map(item => {
                    return {
                        ...rut,
                        ...item,
                        amount: (scope * Number(item.num)).toFixed(2)
                    }
                })
                detailList = list.concat(detailList)
                this.$set(this.ruleForm, 'diseaseDealDetailList', detailList)
                this.$set(this.ruleForm, 'prescriptionId', e)
                this.$set(this.ruleForm, 'prescriptionName', rut.prescriptionName)
            } else {
                let list = this.ruleForm.diseaseDealDetailList || [];
                this.ruleForm.diseaseDealDetailList = list.filter(e => {
                    return !e.prescriptionId
                })
            }
        },
        getMaterial() {
            this.ruleForm.diseaseDealDetailList.forEach(item => {
                let result = this.materialList.find(obj => obj.materialNo == item.materialNo);
                console.log(result)
                item.unitName = result && result.unitName ? result.unitName : '克';
            })
        },
        async getDiseaseDealDetailList() {
            this.tableData = [];
            let res = await diseaseFollowUp.queryByCondition({
                diseaseRecordId: this.ruleForm.diseaseRecordId
            });
            this.tableData = res.data || [];
            let todayDurgList = this.tableData.filter(e => {
                return this.isToday(e.dealDate) && e.prescriptionId
            })
            if (this.ruleForm.dealDate && this.isToday(this.ruleForm.dealDate)) {
                this.judgeMedication(todayDurgList);
            }
        },
        //判断是否用药
        //todayDurgList今天用过处方的所有记录
        async judgeMedication(todayDurgList) {
            //判断最后一次记录是否是今天
            if (todayDurgList.length > 0) {
                //根据最近一次用药判断记录中是否有处方
                this.$confirm('今天已经使用过处方,如果继续系统将匹配下一日处方药物,是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.handleChangePrescription(this.ruleForm.prescriptionId);
                }).catch(() => {
                    this.handleChangePrescription();
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            } else {
                this.handleChangePrescription(this.ruleForm.prescriptionId);
            }

        },
        isToday(dateString) {
            const today = new Date();
            const givenDate = new Date(dateString);
            return (
                givenDate.getFullYear() === today.getFullYear() &&
                givenDate.getMonth() === today.getMonth() &&
                givenDate.getDate() === today.getDate()
            );
        },
        getPrescriptionDetailListId(list) {
            let durgList = list.filter(e => e.prescriptionDetailId)
            return durgList.map(e => e.prescriptionDetailId)
        },
        handleClick(row) {
            let diseaseDealId = row.diseaseDealId;
            if (!diseaseDealId) return;
            diseaseFollowUp.diseaseDealDetailList({ diseaseDealId }).then(res => {
                this.tableDataDiseaseDeal = res.data || []
                if (this.tableDataDiseaseDeal.length) {
                    this.innerVisible = true;
                } else {
                    this.$message.warning('用药记录被清除！')
                }
            }).catch(err => {
                console.log(err)
            })
        },
        handleChangePerson(id) {
            let row = this.person.find(item => Number(item.person.personNo) == id);
            this.$set(this.ruleForm, 'staffName', row.person.name);
        },
        handleGetMaterialName(no) {
            console.log(no)
            let row = this.materialList.find(item => Number(item.materialNo) == Number(no));
            return row.materialName;
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (this.ruleForm.diseaseDealDetailList && this.ruleForm.diseaseDealDetailList.length > 0) {
                        this.ruleForm.diseaseDealDetailList.forEach(item => {
                            item.materialName = this.handleGetMaterialName(item.materialNo)
                        })
                    }
                    let prescriptionDetailListId = this.getPrescriptionDetailListId(this.ruleForm.diseaseDealDetailList)
                    let params = {
                        dealDate: this.ruleForm.dealDate,
                        diseaseDealDetailList: this.ruleForm.diseaseDealDetailList,
                        diseaseRecordId: this.ruleForm.diseaseRecordId,
                        staffName: this.ruleForm.staffName,
                        staffId: this.ruleForm.staffId,
                        waterTemperature: Number(this.ruleForm.waterTemperature),
                        prescriptionDetailListId: prescriptionDetailListId,
                        prescriptionId: prescriptionDetailListId.length > 0 ? this.ruleForm.prescriptionId : '',
                        prescriptionName: prescriptionDetailListId.length > 0 ? this.ruleForm.prescriptionName : ''
                    }
                    this.addEditApi({ ...params }).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败'
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg)
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        addMaterial() {
            let length = this.ruleForm.diseaseDealDetailList?.length || 0
            if (length) {
                this.$set(this.ruleForm.diseaseDealDetailList, length, {
                    materialNo: '',
                    materialName: '',
                    amount: '',
                    usage: '',
                    unitName: ''
                })
            }
        },
        delMaterial(index) {
            let list = this.ruleForm.diseaseDealDetailList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'diseaseDealDetailList', list)
        },
        //重置
        resetForm() {
            this.notUseMaterial = [];
            this.useMaterial = [];
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.hasWaterTemperature = true;
            this.tableData = [];
            this.resetForm();
            this.$emit("closeDialog");
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>

<style lang="scss" scoped>
.diseaseFollowUpList {
    margin-top: 10px;

    .label {
        line-height: 30px;
        font-size: 14px;
        color: #606266;
        font-weight: bolder;
    }
}
</style>